package com.sari.common.security;

import com.sari.common.utils.SpringContextHolder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

//import com.sari.modules.entity.SysRole;

/**
 * 系统安全认证实现类
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(SystemAuthorizingRealm.class);

   // private UserService userService;

    /**
     * 认证回调函数, 登录时调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException{
        logger.debug("调用doGetAuthenticationInfo（）方法");
        return null;
       // SysUser user = getUserService().getUserByLoginName(authcToken.getPrincipal().toString());
//        logger.debug("user:"+user);
//        if (user != null) {
//            return new SimpleAuthenticationInfo(new Principal(user), user.getPassword(), getName());
//        } else {
//            throw new UnknownAccountException();
//        }
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.debug("调用doGetAuthorizationInfo（）方法");

        //String roleId = UserUtils.getCache(UserUtils.CACHE_ROLEID).toString();

            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

//            if (roleId==1) {
//                info.addStringPermission("admin");
//                info.addStringPermission("overviews");
//            }
            return info;
    }

    /**
     * 设定Password校验.
     */
    @PostConstruct
    public void initCredentialsMatcher() {
    //该句作用是重写shiro的密码验证，让shiro用我自己的验证
        setCredentialsMatcher(new CustomCredentialsMatcher());
    }

    /**
     * 设定密码校验的Hash算法与迭代次数
     */
//    @PostConstruct
//    public void initCredentialsMatcher() {
//        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserService.HASH_ALGORITHM);
//        matcher.setHashIterations(UserService.HASH_INTERATIONS);
//        setCredentialsMatcher(matcher);
//    }

    /**
     * 清空用户关联权限认证，待下次使用时重新加载
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清空所有关联认证
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }

    /**
     * 获取系统业务对象
     */
//    public UserService getUserService() {
//        if (userService == null) {
//            userService = SpringContextHolder.getBean(UserService.class);
//        }
//        return userService;
//    }

    /**
     * 授权用户信息
     */
//    public static class Principal implements Serializable {
//
//        private static final long serialVersionUID = 1L;
//
//        private String loginName;
//        private String name;
//        private Map<String, Object> cacheMap;
//
//        public Principal(SysUser user) {
//            this.loginName = user.getUserName();
//            this.name = user.getRealName();
//        }
//
//        public String getLoginName() {
//            return loginName;
//        }
//
//        public String getName() {
//            return name;
//        }
//
//        public Map<String, Object> getCacheMap() {
//            if (cacheMap == null) {
//                cacheMap = new HashMap<String, Object>();
//            }
//            return cacheMap;
//        }
//
//    }
}
